package com.ydsungan.controller;

import com.ydsungan.common.JSONResult;
import com.ydsungan.pojo.*;
import com.ydsungan.service.BookService;
import com.ydsungan.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(path = "/file")
@Api(value = "文件相关",tags = {"与文件相关的接口"})
@CrossOrigin
public class FileController extends BasicController{

    @Autowired
    private FileService fileService;


    @ApiOperation(value="列举文件",notes = "列举所有文件")
    @RequestMapping(value = "/listfile", method = RequestMethod.GET)
    public JSONResult selectFile() throws Exception{

        FileExample fileExample = new FileExample();
        FileExample.Criteria criteria = fileExample.createCriteria();
        fileExample.setOrderByClause("category asc");
        List<File> list = fileService.listFile(fileExample);
        return JSONResult.ok(list);
    }

    @ApiOperation(value="列举类型",notes = "列举所有文件类型")
    @RequestMapping(value = "/listcategory", method = RequestMethod.GET)
    public JSONResult selectCategory() throws Exception{

        CategoryExample categoryExample = new CategoryExample();
        List<Category> list = fileService.listCategory(categoryExample);
        return JSONResult.ok(list);
    }

    @ApiOperation(value="标记失效",notes = "若有文件链接失效，则标记")
    @RequestMapping(value = "/mark", method = RequestMethod.GET)
    public JSONResult markFile(String bookId, String mark, String counts) throws Exception{

        File file = fileService.selectFileById(Integer.parseInt(bookId));
        if(mark != null){
            file.setMark(file.getMark() + 1);
        }
        if(counts != null){
            file.setDownloadCounts(file.getDownloadCounts() + 1);
        }
        fileService.updateFileByExample(file);
        return JSONResult.ok();
    }

    @ApiOperation(value="文件查找",notes = "文库文件搜索框功能实现")
    @RequestMapping(value = "/findfile", method = RequestMethod.GET)
    public JSONResult findFile(String key) throws Exception{

        FileExample fileExample = new FileExample();
        FileExample.Criteria criteria = fileExample.createCriteria();
        fileExample.setOrderByClause("category asc");
        criteria.andFileNameLike("%"+key.trim()+"%");
        List<File> list = fileService.listFile(fileExample);
        return JSONResult.ok(list);
    }




}
